import 'package:flutter/material.dart';
import 'package:flutter_mes_app/common/index.dart';
import 'package:get/get.dart';

class LoginController extends GetxController {
  LoginController();

  /// 表单 key
  GlobalKey formKey = GlobalKey<FormState>();

  /// 用户名
  TextEditingController userNameController =
      TextEditingController(text: "admin");

  /// 密码
  TextEditingController passwordController =
      TextEditingController(text: "EBGyj@2025");

  _initData() {
    update(["login"]);
  }

  // 登录
  Future<void> onSignIn() async {
    if ((formKey.currentState as FormState).validate()) {
      try {
        Loading.show();

        // api 请求
        UserTokenModel res = await UserApi.login(UserLoginReq(
          username: userNameController.text,
          password: passwordController.text,
        ));
        print('登录res->:${res.accessToken}');
        // 本地保存 token
        await UserService.to.setToken(res.accessToken!);
        // 获取用户资料
        await UserService.to.getProfile();

        Loading.success();
        // 跳转首页
        Get.offAllNamed(RouteNames.systemMain);
      } catch (e) {
        print('err$e');
      } finally {
        Loading.dismiss();
      }
    }
  }

  void onTap() {}

  // @override
  // void onInit() {
  //   super.onInit();
  // }

  @override
  void onReady() {
    super.onReady();
    _initData();
  }

  // @override
  // void onClose() {
  //   super.onClose();
  // }
}
